﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using Common;

/// <summary>
///LogInUtil 的摘要说明
/// </summary>
public class LoginUtil
{

    /// <summary>
    /// 登录认证
    /// </summary>
    public static void NeedLogin(string returnURL, Page page)
    {
        object token = HttpContext.Current.Request.Cookies["token"];
        if (token==null ||(token!=null && token.ToString().Length==0))
        {
            TaoBao tb=new TaoBao();
            string url = tb.GetCodeUrl();
            HttpContext.Current.Response.Redirect(url, true);
        }
    }
    /// <summary>
    /// 登录认证
    /// </summary>
    public static void NeedLogin(Page page)
    {
        NeedLogin(HttpContext.Current.Request.RawUrl, page);
    }
    /// <summary>
    /// 退出登录
    /// </summary>
    public static void Logout(string returnURL)
    {
        DeleteCookie("tbuid");
        if (HttpContext.Current.Request.IsAuthenticated)
        {
            HttpContext.Current.Session.RemoveAll();
            HttpContext.Current.Session.Abandon();

            FormsAuthentication.SignOut();
        }
        if (!string.IsNullOrEmpty(returnURL))
        {
            HttpContext.Current.Response.Redirect(returnURL);
        }
    }
    /// <summary>
    /// 退出登录
    /// </summary>
    public static void Logout()
    {
        Logout("~/WeiBoTuiGUang.aspx");
    }

    public static void DeleteCookie(string cookieName = "")
    {
        HttpCookie aCookie;
        if (cookieName.Length == 0)//清除全部cookie
        {
            int limit = HttpContext.Current.Request.Cookies.Count;
            for (int i = 0; i < limit; i++)
            {
                cookieName = HttpContext.Current.Request.Cookies[i].Name;
                aCookie = new HttpCookie(cookieName) { Expires = DateTime.Now.AddDays(-1) };
                HttpContext.Current.Response.Cookies.Add(aCookie);
            }
        }
        else
        {
            aCookie = new HttpCookie(cookieName) { Expires = DateTime.Now.AddDays(-1) };
            HttpContext.Current.Response.Cookies.Add(aCookie);
        }
    }
}